﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;

namespace PhotoGallery.Models.Utils
{
    public class ThumbCreator
    {
        public static string Create(string path, string fileName)
        {
            if (!File.Exists(HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe")))
            {
                return "";
            }
            Process ffmpeg;

            string video;
            string thumb;

            video = path + fileName;

            string tmpFileName = System.IO.Path.GetFileName(fileName);
            string name = System.IO.Path.GetFileNameWithoutExtension(tmpFileName);
            string extention = System.IO.Path.GetExtension(tmpFileName);

            thumb = path + "tmp_"+ name + ".jpg";
            
            ffmpeg = new Process();
            ffmpeg.StartInfo.Arguments = " -i \"" + video + "\"   -vframes 1 -f image2 -vcodec mjpeg \"" + thumb + "\""; // arguments !
            
            ffmpeg.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe");
            ffmpeg.Start();
            ffmpeg.WaitForExit();
            return thumb;
        }

        public static void Convert(string path, string fileName)
        {
            if (!File.Exists(HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe")))
            {
                return;
            }
            //Process ffmpeg;

            string video;
            
            video = path + fileName;

            string tmpFileName = System.IO.Path.GetFileName(fileName);
            string name = System.IO.Path.GetFileNameWithoutExtension(tmpFileName);
            string extention = System.IO.Path.GetExtension(tmpFileName);
            string output = path + name + ".webm";
            
            //ffmpeg = new Process();
            //string ffmpeg_exe = HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe");
            //ffmpeg.StartInfo.Arguments = ffmpeg_exe+" -i " + video + " \\  -acodec libvorbis -ac 2 -ab 96k -ar 44100 \\  -b 345k -s 640x360 " + output;
            //ffmpeg.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe");
            //ffmpeg.Start();

            string param ;
            //param = " -i " + video + " \\  -acodec libvorbis -ac 2 -ab 96k -ar 44100 \\  -b 345k -s 640x360 " + output;
            //param = " -i " + video + " -c:v libvpx -quality good -cpu-used 0 -b:v 7000k -qmin 10 -qmax 42 -maxrate 500k -bufsize 1500k -threads 8 -vf scale=-1:1080 -c:a libvorbis -b:a 192k -f webm "+output;
            //param = " -i " + video + " -b 1500k -vcodec libvpx -acodec libvorbis -ab 160000 -f webm    -g 30 -s 640x360 " + output;
              param = " -i " + video + " -b 1500k -vcodec libvpx -acodec libvorbis -ab 160000 -f webm    -g 30 -s 640x360" + output;
             
            //RunProcess(param);
              Process ffmpeg;
              ffmpeg = new Process();
              ffmpeg.StartInfo.Arguments = " -i " + video + " -b 1500k -vcodec libvpx -acodec libvorbis -ab 160000 -f webm    -g 30 -s 640x360" + output; // arguments !

              ffmpeg.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe");
              ffmpeg.Start(); 

        }


        //public bool GetVideoThumbnail(string inputPath, string saveThumbnailTo)
        //{
        //    //if (!input.infoGathered)
        //    //{
        //    //    GetVideoInfo(input);
        //    //}
        //    int secs;
        //    //divide the duration in 3 to get a preview image in the middle of the clip
        //    //instead of a black image from the beginning.
        //    secs = 1; //(int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);
        //    string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", inputPath, saveThumbnailTo, secs);
        //    string output = RunProcess(Params);

        //    if (File.Exists(saveThumbnailTo))
        //    {
        //        return true;
        //    }
        //    else
        //    {
        //        //try running again at frame 1 to get something
        //        Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", inputPath, saveThumbnailTo, 1);
        //        output = RunProcess(Params);

        //        if (File.Exists(saveThumbnailTo))
        //        {
        //            return true;
        //        }
        //        else
        //        {
        //            return false;
        //        }
        //    }
        //}

        private static string RunProcess(string Parameters)
        {
            //create a process info
            string FFmpegPath = HttpContext.Current.Server.MapPath("~/bin/ffmpeg.exe");
            ProcessStartInfo oInfo = new ProcessStartInfo(FFmpegPath, Parameters);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;

            //Create the output and streamreader to get the output
            string output = null; StreamReader srOutput = null;

            //try the process
            try
            {
                //run the process
                Process proc = System.Diagnostics.Process.Start(oInfo);

                proc.WaitForExit();

                //get the output
                srOutput = proc.StandardError;

                //now put it in a string
                output = srOutput.ReadToEnd();

                proc.Close();
            }
            catch (Exception)
            {
                output = string.Empty;
            }
            finally
            {
                //now, if we succeded, close out the streamreader
                if (srOutput != null)
                {
                    srOutput.Close();
                    srOutput.Dispose();
                }
            }
            return output;
        }
        
    }
}